package com.bifang.common.helper;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

/** 从applicationContext中得到Bean 工具类 */
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean(String beanName) {
        return context != null ? context.getBean(beanName) : null;
    }

    public static Class getClass(String beanName) {
        return context != null ? context.getType(beanName) : null;
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> var1) {
        return context != null ? context.getBeansWithAnnotation(var1) : null;
    }

    /**
     * 通过class获取Bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return context.getBean(name, clazz);
    }

    public static Method getMethod(Class clazz, String methodName) {
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
        Method ret = null;
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                // 调用这个方法，invoke第一个参数是类名，后面是方法需要的参数
                ret = method;
                break;
            }
        }
        return ret;
    }
}
